<?php

class CategoryAction extends CommonAction {
    
    public function _initialize(){
        parent::_initialize();
    } 
    
    public function index(){
        
        $this->display('index');
    }
    
    public function getTree(){
        $model = M('Category');
        $rows = $model->order('parent_id,position asc')->select();
        $list = list_to_tree($rows, 'category_id', 'parent_id', 'children');
        echo json_encode($list);
    }
    
    public function getCombotree(){
        $model = M('Category');
        $rows = $model->field('category_id as id,category_name as text,parent_id as pid,position')->order('pid,position asc')->select();
        $list = list_to_tree($rows, 'id', 'pid', 'children');
        echo json_encode($list);
    }
    
    public function delete(){
        $id = $this->_post('category_id');
        if(!$id || $id < 2) {
            $this->error(L('common_failed'));
        }
        $model = M('Category');
        $childs = $model->where("parent_id = " . $id)->select();
        if($childs) {
            $this->error(L('common_category_has_childs'));
        }

        $rs = $model->where("category_id = " . $id)->delete();
        if($rs) {
            $this->success(L('common_delete_success'));
        } else {
            $this->error(L('common_delete_failed'));
        }
        
    }
    
    public function insertCategory(){
        $model = D('Category');
        if ($vo = $model->create()) {
            $category_id = $this->_post('category_id');
            if($category_id) {
                $result = $model->save();
                if ($result !== false) {
                    $this->clearRedisByAction();
                    $this->success(L('common_update_success'));
                } else {
                    $this->error(L('common_update_failed'));
                }
            } else {
                $lastInsertId = $model->add();
                if ($lastInsertId !== false) {
                    $this->clearRedisByAction();
                    $this->success(L('common_insert_success'));
                } else {
                    $this->error(L('common_insert_failed'));
                }
            }
        } else {
            $this->error($model->getError());
        }
    }
}
?>
